import ubluetooth
import time
from micropython import const
import ubinascii


def hex_to_bytes(hex_string):
    hex_string = hex_string.replace(' ', '')
    if len(hex_string) % 2 != 0:
        raise ValueError("Hex string must have an even number of characters")
    return bytes(int(hex_string[i:i+2], 16) for i in range(0, len(hex_string), 2))



_IRQ_PERIPHERAL_CONNECT = const(7)
_IRQ_GATTC_NOTIFY = const(18)



class Y3Control:

    def __init__(self, mac_str):
        self.addr = hex_to_bytes(mac_str.upper().replace(':', ''))
        self.is_connect = False
        self.callback = None

    def bt_irq(self, event, data):
        if event == _IRQ_GATTC_NOTIFY:
            conn_handle, value_handle, notify_data = data
            key_hex = ubinascii.hexlify(notify_data).upper()
            if self.callback:
                self.callback(key_hex.decode('utf-8'))
        elif event == _IRQ_PERIPHERAL_CONNECT:
            print("已连接设备")
            self.is_connect = True

    def connect(self, callback):
        self.callback = callback
        self.ble = ubluetooth.BLE()
        self.ble.active(True)
        self.ble.irq(self.bt_irq)
        
        while True:
            if not self.is_connect:
                print("正在尝试连接")
                self.ble.gap_connect(0, self.addr)
                time.sleep(2)
            else:
                break


def y3_control_callback(value):
    print(value)


if __name__ == "__main__":
    y3 = Y3Control("11:52:A0:8F:0F:46")
    y3.connect(y3_control_callback)

